package com.zh.recordscreen.util;

import android.app.Activity;
import android.media.MediaRecorder;
import android.os.Environment;
import android.text.format.DateFormat;
import android.util.Log;

import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import java.util.Locale;

/**
 * descrition:录音
 */
public class SoundRecordUtils {
    // 录音功能相关
    MediaRecorder mMediaRecorder; // MediaRecorder 实例
    boolean isRecording; // 录音状态
    String fileName; // 录音文件的名称
    String filePath; // 录音文件存储路径
    Thread timeThread; // 记录录音时长的线程
    int timeCount; // 录音时长 计数
    private static SoundRecordUtils instance = null;
    private SoundRecordUtils(){}
    public static synchronized SoundRecordUtils getInstance(){
        if(instance == null) {
            instance = new SoundRecordUtils();
        }
        return instance;
    }
    public void init(Activity context){
    }
    public void startRecord() {
        // 开始录音
        /* ①Initial：实例化MediaRecorder对象 */
        if (mMediaRecorder == null)
            mMediaRecorder = new MediaRecorder();
        try {
            /* ②setAudioSource/setVedioSource */
            mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);// 设置麦克风
            /*
             * ②设置输出文件的格式：THREE_GPP/MPEG-4/RAW_AMR/Default THREE_GPP(3gp格式
             * ，H263视频/ARM音频编码)、MPEG-4、RAW_AMR(只支持音频且音频编码要求为AMR_NB)
             */
            mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
            /* ②设置音频文件的编码：AAC/AMR_NB/AMR_MB/Default 声音的（波形）的采样 */
            mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
            fileName = DateFormat.format("yyyyMMdd_HHmmss", Calendar.getInstance(Locale.CHINA)) + ".m4a";
//            if (!FileUtils.isFolderExist(FileUtils.getFolderName(audioSaveDir))) {
//                FileUtils.makeFolders(audioSaveDir);
//            }
            filePath = getSaveDirectory()  + fileName;
            /* ③准备 */
            mMediaRecorder.setOutputFile(filePath);
            mMediaRecorder.prepare();
            /* ④开始 */
            mMediaRecorder.start();
        } catch (IllegalStateException e) {
            Log.e("SoundRecordUtils","call startAmr(File mRecAudioFile) failed!" + e.getMessage());
        } catch (IOException e) {
            Log.e("SoundRecordUtils","call startAmr(File mRecAudioFile) failed!" + e.getMessage());
        }
    }

    public void stopRecord() {
        try {
            mMediaRecorder.stop();
            mMediaRecorder.release();
            mMediaRecorder = null;
            filePath = "";
        } catch (RuntimeException e) {
            Log.e("SoundRecordUtils",e.toString());
            mMediaRecorder.reset();
            mMediaRecorder.release();
            mMediaRecorder = null;

            File file = new File(filePath);
            if (file.exists())
                file.delete();

            filePath = "";
        }
    }

    // 记录录音时长
//    private void countTime() {
//        while (isRecording) {
//            Log.e("SoundRecordUtils","正在录音");
//            timeCount++;
//            Message msg = Message.obtain();
//            msg.what = TIME_COUNT;
//            msg.obj = timeCount;
//            myHandler.sendMessage(msg);
//            try {
//                timeThread.sleep(1000);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//        }
//        LogUtil.d("结束录音");
//        timeCount = 0;
//        Message msg = Message.obtain();
//        msg.what = TIME_COUNT;
//        msg.obj = timeCount;
//        myHandler.sendMessage(msg);
//    }

    //获取存储文件夹的位置
    public String getSaveDirectory() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            //如果确认为视频类型，设置根目录，绝对路径下的自定义文件夹中
            String rootDir = Environment.getExternalStorageDirectory()
                    .getAbsolutePath() + "/soundRecord/" ;
            //创建该文件夹
            File file = new File(rootDir);
            if (!file.exists()) {
                //如果该文件夹不存在
                if (!file.mkdirs()) {
                    //如果没有创建成功
                    return null;
                }
            }
            //创建成功了，返回该目录
            return rootDir;
        } else {
            //不是音视频文件，不保存，无路径
            return null;
        }
    }
}
